
import 'dart:async';
import 'dart:collection';

import 'package:isolate_pool_executor/isolate_pool_executor.dart';

import '../pojo/ImPojo.dart';
import '../util/ImSingleton.dart';
import '../util/LoggerUtil.dart';
import 'FileDownloadService.dart';
import 'FileDownloadSocket.dart';

class BatchDownloadService {

  // 保证实例只有唯一一个
  static final BatchDownloadService _BATCH_DOWNLOAD_SERVICE = BatchDownloadService._();

  late IsolatePoolExecutor _threadPool;
  final _LOGGER = createLogger();

  BatchDownloadService._() {
    _init();
  }

  static BatchDownloadService getInstance() {
    return BatchDownloadService._BATCH_DOWNLOAD_SERVICE;
  }

  _init() {
    _threadPool = IsolatePoolExecutor(
        // 核心数量，无任务时一直等待，需要shutdown后才会销毁
        corePoolSize: 2,
        // 总数 超过核心数之后的空闲一段时间后会自动销毁
        maximumPoolSize: 8,
        //非核心的isolate空闲等待时间
        keepAliveTime: const Duration(minutes: 1),
        // 任务寄放队列
        taskQueue: Queue(),
        // 当队列添加失败时的处理方式
        handler: RejectedExecutionHandler.callerRunsPolicy
    );
  }

  void downFile(ImMessage message, DownloadCallback callback) async {
    var ip = ImSingleton.getInstance().session.getData("im_ip") as String;
    _LOGGER.i("batch downFile, $ip", time: DateTime.now());
    // _threadPool.compute(_downFile, _DownloadFileParam(message, callback, ip));
  }

  Future<bool> _downFile(_DownloadFileParam param) async {
    await FileDownloadService.downFile(param.message, param.callBack, param.downServerIp);
    return true;
  }
}

class _DownloadFileParam {
  ImMessage message;
  DownloadCallback callBack;
  String downServerIp;

  _DownloadFileParam(this.message, this.callBack, this.downServerIp);
}